#===============================================================================
# EventScripts compatibility layer
#===============================================================================
class ServerVar(object):
    """
    @note: FROM es.py
    Intelligent class to wrap a specific server variable
    """
    def __init__(self, value):
        self.value = value
            
    def __str__(self):
        return str(self.value)
        
    def __float__(self):
        return float(self.value)
        
    def __int__(self):
        return int(self.value)
        
    def __nonzero__(self):
        return bool(float(self.value))
        
    def __coerce__(self, other):
        if isinstance(other, str):
            return str(self), other
        elif isinstance(other, int):
            return int(self), other
        elif isinstance(other, float):
            return float(self), other
        elif isinstance(other, bool):
            return bool(self), other
        else:
            return None


class PseudoES(object):
    """
    A pseudo ES, implementing the methods and classes used in utils.
    """
    
    _msg_prefix_aliases = {-1: 'ERR:', 0: 'MSG:' , 1: 'DBG:'}
    _debug_level = -1
    _event_cache = {}
    _event_listeners = {}
    
    class PseudoAddons(object):
        def __init__(self):
            self.EventListeners = {}
            
        def registerForEvent(self, listener, eventname, callback):
            """
            register a listener for a specific event
            """
            if not self.EventListeners.has_key(eventname):
                self.EventListeners[eventname] = {}
            self.EventListeners[eventname][listener] = callback

        def unregisterForEvent(self, listener, eventname):
            """
            unregister a listener
            """
            if not self.EventListeners.has_key(eventname):
                return
            if self.EventListeners[eventname].has_key(listener):
                del self.EventListeners[eventname][listener]
                
        def triggerEvent(self, eventname, event_var):
            """
            triggers an event
            """
            if not self.EventListeners.has_key(eventname):
                return
            for listener in self.EventListeners[eventname]:
                self.EventListeners[eventname][listener](event_var)
    addons = PseudoAddons()
    
    class PseudoServer(object):
        def queuecmd(self, command):
            pass
    server = PseudoServer()
    
    def dbgmsg(self, level, message):
        if level <= self._debug_level:
            prefix = self._msg_prefix_aliases.get(level, 'MSG:')
            print '%s%s' % (prefix, message)
        
    _available_server_vars = {'eventscripts_gamedir': '.'}
        
    def ServerVar(self, name, value=''):
        return ServerVar(self._available_server_vars.get(name, value))
    
    def event(self, command, name, key=None, value=None):
        command = command.lower()
        if command == 'initialize':
            self._event_cache[name] = {}
        elif command.startswith('set'):
            self._event_cache[name][str(key)] = str(value)
        elif command == 'fire':
            self.addons.triggerEvent(name, self._event_cache[name])
            del self._event_cache[name]

try:
    import es
except ImportError:
    es = PseudoES()

def debug(message):
    es.dbgmsg(1, message)
    
def msg(message):
    es.dbgmsg(0, message)
    
def error(message):
    es.dbgmsg(-1, message)
    
def set_debuglevel(level):
    if isinstance(es, PseudoES):
        es._debug_level = level
    else:
        es.server.queuecmd("eventscripts_debug %s" % level)
    
#===============================================================================
# Commandlib compatibility layer
#===============================================================================

class PseudoCmdlib(object):
    def registerServerCommand(self, name, func, description):
        pass
    def registerSayCommand(self, name, func, description):
        pass
    def registerClientCommand(self, name, func, description):
        pass
    def unregisterServerCommand(self, name):
        pass
    def unregisterSayCommand(self, name):
        pass
    def unregisterClientCommand(self, name):
        pass
    
try:
    import cmdlib
except ImportError:
    cmdlib = PseudoCmdlib()
    
#===============================================================================
# Gamethread compatibility layer
#===============================================================================

class PseudoGamethread(object):
    def delayedname(self, seconds, name, func, args=(), kwargs={}):
        import time
        time.sleep(seconds)
        func(*args, **kwargs)
        
    def cancelDelayed(self, name):
        pass
    
try:
    import gamethread
except ImportError:
    gamethread = PseudoGamethread()